package cn.huiyunche.driver.service.impl;

import cn.huiyunche.base.service.enums.TmsBillDetailEnum;
import cn.huiyunche.base.service.interfaces.DriverBillDetailsService;
import cn.huiyunche.base.service.interfaces.UserService;
import cn.huiyunche.base.service.mappers.CMdvBillSummaryMapper;
import cn.huiyunche.base.service.mappers.DWaybillMapper;
import cn.huiyunche.base.service.model.*;
import cn.huiyunche.base.service.vo.Result;
import cn.huiyunche.base.service.vo.UserVo;
import cn.huiyunche.driver.service.CMdvBillDetailService;
import cn.huiyunche.driver.service.CMdvBillSummaryService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


/**
 * @FileName: cn.huiyunche.driver.service.impl
 * @Description: Description
 * @author: ligl
 * @date: 2017/3/9 上午11:59
 */
@Service
public class CMdvBillSummaryServiceImpl implements CMdvBillSummaryService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CMdvBillSummaryServiceImpl.class);

    @Autowired
    private CMdvBillSummaryMapper cMdvBillSummaryMapper;

    @Autowired
    private DWaybillMapper dWaybillMapper = null;

    @Autowired
    private CMdvBillDetailService cMdvBillDetailService;

    @Autowired
    private UserService userService = null;
    @Autowired
    private DriverBillDetailsService driverBillDetailsService;

    private UserService getUserService() {
        return this.userService;
    }


    @Override
    public Long add(CMdvBillSummary cMdvBillSummary) {
        LOGGER.info("DRouteServiceImpl.add params : {}", cMdvBillSummary);

        if (null == cMdvBillSummary) {
            LOGGER.error("CMdvBillSummaryService.add param form must not be null");
            throw new IllegalArgumentException("账单不能为空");
        }

        cMdvBillSummaryMapper.insertSelective(cMdvBillSummary);
        return cMdvBillSummary.getId();
    }


    @Override
    public List<CMdvBillSummary> selectByExample(CMdvBillSummaryExample summaryExample) {
        return cMdvBillSummaryMapper.selectByExample(summaryExample);
    }


    @Override
    public Result<Object> getSummaryList(String beginDate, String endDate) throws Exception {
        //判断是否是周四之前，周四之前查询上上周的周一到周日(false)，周四之后则查询上周的周一到周日(true)
        Boolean beforeOrAfter = DateTime.now().compareTo(DateTime.now().withDayOfWeek(5).hourOfDay().withMinimumValue().minuteOfHour().withMinimumValue()
                .secondOfMinute().withMinimumValue().millisOfSecond().withMinimumValue())>=0;


        //如果传入默认日期，开始时间为空
        if(StringUtils.isBlank(beginDate)||"".equals(beginDate)||beginDate.length()==0){
            beginDate = beforeOrAfter == true? DateTime.now().withDayOfWeek(1).minusDays(7).toString("yyyy-MM-dd"):DateTime.now().withDayOfWeek(1).minusDays(14).toString("yyyy-MM-dd");

        }else{
            beginDate = DateTime.now().withDayOfWeek(1).minusDays(7).toString("yyyy-")+ beginDate.replaceAll("/","-");
        }
        //如果传入默认日期,结束时间为空
        if(StringUtils.isBlank(endDate)||"".equals(beginDate)||endDate.length()==0){
            endDate =  beforeOrAfter == true? DateTime.now().withDayOfWeek(1).minusDays(1).toString("yyyy-MM-dd"):DateTime.now().withDayOfWeek(1).minusDays(8).toString("yyyy-MM-dd");
        }else{
            endDate = DateTime.now().withDayOfWeek(1).minusDays(7).toString("yyyy-")+ endDate.replaceAll("/","-");
        }

        Result<Object> result = new Result<Object>(false, "查询失败");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日");
        //获取时间列表
        List weekList = this.getWeekList(beforeOrAfter);

        UserVo user = this.getUserService().getCurrentUserVo();
        if (null == user) {
            LOGGER.info("==UserService().getCurrentUserVo=={}", user);
            result.setSuccess(true);
            result.setMessageCode("300");
            result.setMessage("未获取当前用户信息");
            return result;
        }
        CMdvBillSummaryExample summaryExample = new CMdvBillSummaryExample();
        summaryExample.createCriteria().andUserIdEqualTo(user.getId()).andDtUpdateDateGreaterThanOrEqualTo(sdf.parse(beginDate)).andDtUpdateDateLessThanOrEqualTo(sdf.parse(endDate));
        List<CMdvBillSummary> summaryList = cMdvBillSummaryMapper.selectByExample(summaryExample);
        LOGGER.info("==cMdvBillSummaryMapper.selectByExample=={}", summaryList);
        Double amuntAll = 0.00;
        List objList = new ArrayList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("weekList", weekList);
        if (CollectionUtils.isNotEmpty(summaryList) && null != summaryList) {
            for (CMdvBillSummary cMdvBillSummary : summaryList) {
                DWaybill dWaybill = this.getWaybillById(cMdvBillSummary.getWaybillId());
                JSONObject obj = new JSONObject();
                obj.put("orderCode", String.valueOf(dWaybill.getOrderCode()));
                String address = dWaybill.getDepartureProvince() + dWaybill.getDepartureCity() + "-" + dWaybill.getDestProvince() + dWaybill.getDestCity();
                obj.put("lines", address == null ? "" : address);

                obj.put("recoveryTime", dWaybill.getRecoveryTime() == null ? "" : sdf1.format(dWaybill.getRecoveryTime()).toString());
                BigDecimal amunt = this.getAmount(Long.parseLong(cMdvBillSummary.getBillDetailId()));
                obj.put("price", amunt.toString());
                objList.add(obj);
                amuntAll += amunt.doubleValue();
            }
            jsonObject.put("summaryList", objList);
            jsonObject.put("amountPrice", String.valueOf(amuntAll));
            result.setMessageCode("200");
            result.setSuccess(true);
            result.setMessage("查询成功");
        }else {
            jsonObject.put("summaryList", objList);
            result.setMessageCode("400");
            result.setMessage("未查询到账单数据");
        }
        result.setData(jsonObject);
        return result;
    }


    @Override
    public Result<Object> getBillDetailList(Long orderId) throws Exception {
        Result<Object> result = new Result<Object>(false, "查询失败");

        UserVo user = this.getUserService().getCurrentUserVo();
        if (null == user) {
            result.setSuccess(true);
            result.setMessageCode("500");
            result.setMessage("该运单在知车系统中不存在");
            return result;
        }
        DWaybill waybillById = this.getWaybillById(orderId);
        DDriverBillDetails dDriverBillDetails1 = new DDriverBillDetails();
        List<DDriverBillDetails> dDriverBillDetailsList=driverBillDetailsService.getDriverBillDetailsByOrderCode(waybillById.getCusorderno(),waybillById.getOrderCode());
        if (dDriverBillDetailsList.size()>0){
            BigDecimal cashPay=BigDecimal.ZERO;
            BigDecimal fuelPay=BigDecimal.ZERO;
            StringBuffer remarkBuffer = new StringBuffer();
            StringBuffer payDateBuffer = new StringBuffer();
            for (DDriverBillDetails dDriverBillDetails : dDriverBillDetailsList) {
                if (dDriverBillDetails.getCashCost()!=null){
                    cashPay=cashPay.add(new BigDecimal(dDriverBillDetails.getCashCost().toString()));
                }
                if (dDriverBillDetails.getFuelCost()!=null){
                    fuelPay=fuelPay.add(new BigDecimal(dDriverBillDetails.getFuelCost().toString()));
                }
                remarkBuffer.append(dDriverBillDetails.getRemark()+",");
                payDateBuffer.append(dDriverBillDetails.getPayDate()+",");
            }
            if (remarkBuffer.length() > 0) {
                remarkBuffer.deleteCharAt(remarkBuffer.length()-1);
            }
            if (payDateBuffer.length() > 0) {
                payDateBuffer.deleteCharAt(payDateBuffer.length()-1);
            }
            dDriverBillDetails1 = dDriverBillDetailsList.get(0);
            dDriverBillDetails1.setCashCost(cashPay);
            dDriverBillDetails1.setFuelCost(fuelPay);
            dDriverBillDetails1.setRemark(remarkBuffer.toString());
            dDriverBillDetails1.setPayDate(payDateBuffer.toString());
            dDriverBillDetails1.setCashCostPay(cashPay.toString());
            dDriverBillDetails1.setFuelCostPay(fuelPay.toString());
        }
        //获取运单
        //DWaybill dWaybill = this.getByTmsOrderCode(orderCode);
        if (null == dDriverBillDetails1) {
            result.setSuccess(true);
            result.setMessageCode("200");
            result.setMessage("");
            return result;
        }

 //       CMdvBillSummaryExample summaryExample = new CMdvBillSummaryExample();
//        summaryExample.createCriteria().andWaybillIdEqualTo(dWaybill.getId());
//        List<CMdvBillSummary> summaryList = cMdvBillSummaryMapper.selectByExample(summaryExample);
//
//        CMdvBillDetailExample detailExample = new CMdvBillDetailExample();
//        detailExample.createCriteria().andIdEqualTo(Long.parseLong(summaryList.get(0).getBillDetailId()));
//        //获取运单费用list
//        List<CMdvBillDetail> detailList = cMdvBillDetailService.selectByExample(detailExample);
        if (Objects.nonNull(dDriverBillDetails1) && null != dDriverBillDetails1) {
            //JSONObject jsonObject = new JSONObject();
            //jsonObject.put("line", dWaybill.getDepartureProvince() + dWaybill.getDepartureCity() + "-" + dWaybill.getDestProvince() + dWaybill.getDestCity());
//            jsonObject.put("price", detailList.get(0).getDcPay().toString());
//            jsonObject.put("orderCode", orderCode);
//            jsonObject.put("vehicle", summaryList.get(0).getVcstyleNo());
//            JSONArray jsonArray = this.getDetail(detailList);
            //jsonObject.put("billDetail", jsonArray);
            result.setMessageCode("200");
            result.setSuccess(true);
            result.setMessage("查询成功");
            result.setData(dDriverBillDetails1);
        }

        return result;
    }

    /**
     * 当年日期前🈚五周
     *
     * @return
     */
    private List getWeekList(Boolean beforeOrAfter) {
        List list = new ArrayList<>();
        DateTime now = new DateTime();
        DateTime withDayOfWeek2 = now.withDayOfWeek(1).minusDays(7);
        DateTime withDayOfWeekend2 = now.withDayOfWeek(1).minusDays(1);

        DateTime withDayOfWeek3 = now.withDayOfWeek(1).minusDays(14);
        DateTime withDayOfWeekend3 = now.withDayOfWeek(1).minusDays(8);

        DateTime withDayOfWeek4 = now.withDayOfWeek(1).minusDays(21);
        DateTime withDayOfWeekend4 = now.withDayOfWeek(1).minusDays(15);

        DateTime withDayOfWeek5 = now.withDayOfWeek(1).minusDays(28);
        DateTime withDayOfWeekend5 = now.withDayOfWeek(1).minusDays(22);

        DateTime withDayOfWeek6 = now.withDayOfWeek(1).minusDays(35);
        DateTime withDayOfWeekend6 = now.withDayOfWeek(1).minusDays(29);

        DateTime withDayOfWeek7 = now.withDayOfWeek(1).minusDays(42);
        DateTime withDayOfWeekend7 = now.withDayOfWeek(1).minusDays(36);

        int i = now.compareTo(DateTime.now().withDayOfWeek(5).hourOfDay().withMinimumValue().minuteOfHour().withMinimumValue()
                .secondOfMinute().withMinimumValue().millisOfSecond().withMinimumValue());
        if(beforeOrAfter){
            list.add(withDayOfWeek2.toString("MM/dd") + "-" + withDayOfWeekend2.toString("MM/dd"));
        }
        list.add(withDayOfWeek3.toString("MM/dd") + "-" + withDayOfWeekend3.toString("MM/dd"));
        list.add(withDayOfWeek4.toString("MM/dd") + "-" + withDayOfWeekend4.toString("MM/dd"));
        list.add(withDayOfWeek5.toString("MM/dd") + "-" + withDayOfWeekend5.toString("MM/dd"));
        list.add(withDayOfWeek6.toString("MM/dd") + "-" + withDayOfWeekend6.toString("MM/dd"));
        if (!beforeOrAfter){
            list.add(withDayOfWeek7.toString("MM/dd") + "-" + withDayOfWeekend7.toString("MM/dd"));
        }
        return list;
    }

    /**
     * 获取运单对象
     *
     * @param id 订单id
     * @return 运单对象
     */
    private DWaybill getWaybillById(Long id) {
        DWaybillExample dwe = new DWaybillExample();
        DWaybillExample.Criteria c = dwe.createCriteria();
        c.andIdEqualTo(id).andUserIdGreaterThan(0L);
        List<DWaybill> waybillList1 = this.dWaybillMapper.selectByExample(dwe);
        List<DWaybill> waybillList = waybillList1;
        return waybillList.size() > 0 ? waybillList.get(0) : null;
    }

    /**
     * 获取运单对象
     *
     * @param billDetailId 订单详细id
     * @return 运单对象
     */
    private BigDecimal getAmount(Long billDetailId) {
        BigDecimal amount = new BigDecimal(0);
        CMdvBillDetailExample detailExample = new CMdvBillDetailExample();
        detailExample.createCriteria().andIdEqualTo(billDetailId);

        List<CMdvBillDetail> detailList = cMdvBillDetailService.selectByExample(detailExample);
        if (CollectionUtils.isNotEmpty(detailList) && null != detailList) {
            amount = detailList.get(0).getDcPay();
        }
        return amount;

    }


    /**
     * 获取运单对象
     *
     * @param orderCode 订单编号
     * @return 运单对象
     */
    private DWaybill getByTmsOrderCode(String orderCode) {
        DWaybillExample dwe = new DWaybillExample();
        DWaybillExample.Criteria c = dwe.createCriteria();
        c.andOrderCodeEqualTo(orderCode).andUserIdGreaterThan(0L);
        List<DWaybill> waybillList1 = this.dWaybillMapper.selectByExample(dwe);
        List<DWaybill> waybillList = waybillList1;
        return waybillList.size() > 0 ? waybillList.get(0) : null;
    }

    /**
     * 获得费用list
     *
     * @param detailList
     * @return
     */
    private JSONArray getDetail(List<CMdvBillDetail> detailList) {
        BigDecimal zero = new BigDecimal(0);
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject;
        //里程运费
        if (detailList.get(0).getDcAssesModify().compareTo(zero) != 0) {
            jsonObject = new JSONObject();
            jsonObject.put("name", TmsBillDetailEnum.SHIP_COST.getText());
            jsonObject.put("value", detailList.get(0).getDcAssesModify());
            jsonArray.add(jsonObject);
        }
        //固定运费1
        if (detailList.get(0).getDcFixed1().compareTo(zero) != 0) {
            jsonObject = new JSONObject();
            jsonObject.put("name", TmsBillDetailEnum.DC_FIXED1.getText());
            jsonObject.put("value", detailList.get(0).getDcFixed1());
            jsonArray.add(jsonObject);
        }
        //油耗运费
        if (detailList.get(0).getDctotalFuel().compareTo(zero) != 0) {
            jsonObject = new JSONObject();
            jsonObject.put("name", TmsBillDetailEnum.DCTOTAL_FUEL.getText());
            jsonObject.put("value", detailList.get(0).getDctotalFuel());
            jsonArray.add(jsonObject);
        }
        //固定运费2
        if (detailList.get(0).getDcFixed2().compareTo(zero) != 0) {
            jsonObject = new JSONObject();
            jsonObject.put("name", TmsBillDetailEnum.DC_FIXED2.getText());
            jsonObject.put("value", detailList.get(0).getDcFixed2());
            jsonArray.add(jsonObject);
        }
        //春运补贴
        if (detailList.get(0).getDcFestivalbonus().compareTo(zero) != 0) {
            jsonObject = new JSONObject();
            jsonObject.put("name", TmsBillDetailEnum.DC_FESTIVAL_BONUS);
            jsonObject.put("value", detailList.get(0).getDcFestivalbonus());
            jsonArray.add(jsonObject);
        }
        //综合运费
        if (detailList.get(0).getDcSomebonus().compareTo(zero) != 0) {
            jsonObject = new JSONObject();
            jsonObject.put("name", TmsBillDetailEnum.DC_SOME_BONUS.getText());
            jsonObject.put("value", detailList.get(0).getDcSomebonus());
            jsonArray.add(jsonObject);
        }
        //其它
        if (detailList.get(0).getDcModify().compareTo(zero) != 0) {
            jsonObject = new JSONObject();
            jsonObject.put("name", TmsBillDetailEnum.DC_MODIFY.getText());
            jsonObject.put("value", detailList.get(0).getDcModify());
            jsonArray.add(jsonObject);
        }
        //粗算应付
        if (detailList.get(0).getDcFuel().compareTo(zero) != 0) {
            jsonObject = new JSONObject();
            jsonObject.put("name", TmsBillDetailEnum.DC_FUEL.getText());
            jsonObject.put("value", detailList.get(0).getDcFuel());
            jsonArray.add(jsonObject);
        }
        //油量
        if (detailList.get(0).getDcSum().compareTo(zero) != 0) {
            jsonObject = new JSONObject();
            jsonObject.put("name", TmsBillDetailEnum.DC_FUEL.getText());
            jsonObject.put("value", detailList.get(0).getDcSum());
            jsonArray.add(jsonObject);
        }
        //油价
        if (detailList.get(0).getDcFuelUp().compareTo(zero) != 0) {
            jsonObject = new JSONObject();
            jsonObject.put("name", TmsBillDetailEnum.DC_FUEL_UP.getText());
            jsonObject.put("value", detailList.get(0).getDcFuelUp());
            jsonArray.add(jsonObject);
        }
        //油费
        if (detailList.get(0).getDcFuel().compareTo(zero) != 0) {
            jsonObject = new JSONObject();
            jsonObject.put("name", TmsBillDetailEnum.DC_FUEL_FEE.getText());
            jsonObject.put("value", detailList.get(0).getDcFuel());
            jsonArray.add(jsonObject);
        }
        //应付油费
        if (detailList.get(0).getDcPayRemainFuel().compareTo(zero) != 0) {
            jsonObject = new JSONObject();
            jsonObject.put("name", TmsBillDetailEnum.DC_PAY_REMAIN_FUEL.getText());
            jsonObject.put("value", detailList.get(0).getDcPayRemainFuel());
            jsonArray.add(jsonObject);
        }
        //保险费
        if (detailList.get(0).getDcInsFee().compareTo(zero) != 0) {
            jsonObject = new JSONObject();
            jsonObject.put("name", TmsBillDetailEnum.DC_INS_FEE.getText());
            jsonObject.put("value", detailList.get(0).getDcInsFee());
            jsonArray.add(jsonObject);
        }
        //GPS费
        if (detailList.get(0).getDcGpsFee().compareTo(zero) != 0) {
            jsonObject = new JSONObject();
            jsonObject.put("name", TmsBillDetailEnum.DC_GPS_FEE.getText());
            jsonObject.put("value", detailList.get(0).getDcGpsFee());
            jsonArray.add(jsonObject);
        }
        //奖励金额
        if (detailList.get(0).getDcZhicheBonus().compareTo(zero) != 0) {
            jsonObject = new JSONObject();
            jsonObject.put("name", TmsBillDetailEnum.DC_ZHICHE_BONUS.getText());
            jsonObject.put("value", detailList.get(0).getDcZhicheBonus());
            jsonArray.add(jsonObject);
        }
        //提车考核款
        if (detailList.get(0).getDcAssesModify().compareTo(zero) != 0) {
            jsonObject = new JSONObject();
            jsonObject.put("name", TmsBillDetailEnum.DC_ASSES_MODIFY.getText());
            jsonObject.put("value", detailList.get(0).getDcAssesModify());
            jsonArray.add(jsonObject);
        }
        //运费扣减
        if (detailList.get(0).getDcPayReduce().compareTo(zero) != 0) {
            jsonObject = new JSONObject();
            jsonObject.put("name", TmsBillDetailEnum.DC_PAY_REDUCE.getText());
            jsonObject.put("value", detailList.get(0).getDcPayReduce());
            jsonArray.add(jsonObject);
        }
        //实付运费
        if (detailList.get(0).getDcPay().compareTo(zero) != 0) {
            jsonObject = new JSONObject();
            jsonObject.put("name", TmsBillDetailEnum.DC_PAY.getText());
            jsonObject.put("value", detailList.get(0).getDcPay());
            jsonArray.add(jsonObject);
        }
        //油卡充值
        if (detailList.get(0).getDcPayByOilcard().compareTo(zero) != 0) {
            jsonObject = new JSONObject();
            jsonObject.put("name", TmsBillDetailEnum.DC_PAY_BY_OILCARD.getText());
            jsonObject.put("value", detailList.get(0).getDcPayByOilcard());
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }


}
